using System;
using System.Collections.ObjectModel;
using Microsoft.Practices.Composite.Events;
using uTorrentNetClient.ModelDesign.Contracts;
using uTorrentNetClient.ModelDesign.Events;
using uTorrentNetClient.ModelDesign.Helper;
using System.Linq;

namespace uTorrentNetClient.ModelDesign.NotifyWindow.Model
{
    public class NotifyWindowModel : Base, INotifyWindowModel
    {
        public ObservableCollection<SpeedHelper> SpeedDown { get; set; }
        public ObservableCollection<SpeedHelper> SpeedUp { get; set; }

        private string _toolTip;
        public string ToolTip
        {
            get { return _toolTip; }
            set
            {
                _toolTip = value;
                SetNotifyPropertyChanged("ToolTip");
            }
        }

        public NotifyWindowModel(IEventAggregator eventAggregator)
        {
            SpeedDown = new ObservableCollection<SpeedHelper>();
            SpeedUp = new ObservableCollection<SpeedHelper>();

            eventAggregator.GetEvent<UpdateSpeedDownInfoEvent>().Subscribe(addSpeedDown);
            eventAggregator.GetEvent<UpdateSpeedUpInfoEvent>().Subscribe(addSpeedUp);
            eventAggregator.GetEvent<UpdateNotifyToolTipInfoEvent>().Subscribe(setToolTip);

            for (int i = 0; i < 10; i++)
            {
                addSpeedDown(new SpeedHelper(DateTime.Now.AddDays(-i), 0));
                addSpeedUp(new SpeedHelper(DateTime.Now.AddDays(-i), 0));
            }
        }

        private void addSpeedDown(SpeedHelper speedHelper)
        {
            if(SpeedDown.Count >= 10)
            {
                var rItem = SpeedDown.FirstOrDefault(x => x.Time == SpeedDown.Min(y => y.Time));
                if (rItem != null)
                    SpeedDown.Remove(rItem);
            }
            SpeedDown.Add(speedHelper);
        }

        private void addSpeedUp(SpeedHelper speedHelper)
        {
            if (SpeedUp.Count >= 10)
            {
                var rItem = SpeedUp.FirstOrDefault(x => x.Time == SpeedUp.Min(y => y.Time));
                if (rItem != null)
                    SpeedUp.Remove(rItem);
            }
            SpeedUp.Add(speedHelper);
        }

        private void setToolTip(string toolTip)
        {
            ToolTip = toolTip;
        }
    }
}